package com.lty.jeeg.server.modules.sys.service.impl;

import java.util.List;

import com.lty.jeeg.server.common.enums.ResponseEnum;
import com.lty.jeeg.server.modules.sys.dao.DeptDao;
import com.lty.jeeg.server.modules.sys.dao.UserDao;
import com.lty.jeeg.server.modules.sys.model.Dept;
import com.lty.jeeg.server.modules.sys.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author : LTY
 * @date : 2018-12-05 09:42:50
 * Description :
 */
@Service
@Slf4j
public class DeptServiceImpl implements DeptService {

    private final DeptDao deptDao;
    private final UserDao userDao;

    @Autowired
    public DeptServiceImpl(DeptDao deptDao, UserDao userDao) {
        this.deptDao = deptDao;
        this.userDao = userDao;
    }

    @Override
    public Dept getById(Long id) {
        Dept dept = deptDao.getById(id);
        if (dept.getParentId() == 0) {
            dept.setParentName("总公司");
        }
        return dept;
    }

    @Override
    public Dept getParentById(Long id) {
        return deptDao.getParentById(id);
    }

    @Override
    public ResponseEnum delete(Long id) {
        Integer count = userDao.countUser(id);
        if (count > 0) {
            return ResponseEnum.DEPT_USER_EXIST_ERROR;
        } else {
            log.debug("删除Dept=>{}", id);
            deptDao.delete(id);
            return ResponseEnum.SUCCESS;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(Dept dept) {
        Long parentId = dept.getParentId();
        if (parentId == 0) {
            dept.setParentIds("0,");
        } else {
            Dept parentDept = deptDao.getById(parentId);
            dept.setParentIds(parentDept.getParentIds() + parentDept.getId() + ",");
        }
        dept.preUpdate();

        log.debug("修改Dept=>{}", dept.getId());
        return deptDao.update(dept);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long save(Dept dept) {
        Long parentId = dept.getParentId();
        if (parentId == 0) {
            dept.setParentIds("0,");
        } else {
            Dept parentDept = deptDao.getById(parentId);
            dept.setParentIds(parentDept.getParentIds() + parentDept.getId() + ",");
        }

        dept.preInsert();

        deptDao.save(dept);
        log.debug("新增Dept=>{}", dept.getId());
        return dept.getId();
    }

    @Override
    public List<Dept> treeList() {
        return deptDao.treeList();
    }


    @Override
    public List<Dept> fasList() {
        return deptDao.fasList();
    }

    @Override
    public List<Dept> listAll() {
        return deptDao.listAll();
    }

    @Override
    public List<Dept> fasListAll() {
        return deptDao.fasListAll();
    }

}
